package com.pro01.backend.interceptor;

import com.pro01.backend.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class JwtInterceptor implements HandlerInterceptor {

//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//
//        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
//            // 跨域预检请求，直接放行
//            return true;
//        }
//        // 获取 Token
//        String token = request.getHeader("Authorization");
//
//        // 验证 Token
//        Map<String, Object> claims = JwtUtil.parseToken(token);
//        if (claims == null) {
//            response.setStatus(401);
//            response.getWriter().write("Unauthorized: Invalid Token");
//            return false;
//        }
//
//        // 验证通过，继续请求
//        return true;
//    }
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

    if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
        return true;
    }

    String token = request.getHeader("Authorization");

    Map<String, Object> claims = JwtUtil.parseToken(token);
    if (claims == null) {
        // 设置响应头和内容类型
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write("{\"code\":401, \"message\":\"Token 已过期或无效\"}");
        return false;
    }

    return true;
}

}
